package com.b2c.erp.controller.fahuo;

import com.b2c.common.utils.DateUtil;
import com.b2c.common.utils.OrderNumberUtils;
import com.b2c.entity.datacenter.DcShopEntity;
import com.b2c.entity.erp.enums.ContactTypeEnum;
import com.b2c.entity.erp.enums.InvoiceTransTypeEnum;
import com.b2c.interfaces.ExpressCompanyService;
import com.b2c.interfaces.ShopService;
import com.b2c.interfaces.wms.ContactService;
import com.b2c.interfaces.fahuo.OrderSendService;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.ContactEntity;

import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 描述：
 * 订单Controller
 *
 * @author qlp
 * @date 2019-06-03 10:47
 */
@RequestMapping("/fahuo")
@Controller
public class OrderSendController {
    @Autowired
    private OrderSendService orderSendService;
    @Autowired
    private ContactService contactService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private ExpressCompanyService expressCompanyService;

    Logger log = LoggerFactory.getLogger(OrderSendController.class);

    /***
     * 订单列表
     * 
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/order_send_list", method = RequestMethod.GET)
    public String orderList(Model model, HttpServletRequest request) {
        Integer pageIndex = 1;
        Integer pageSize = DataConfigObject.getInstance().getPageSize();

        if (StringUtils.isEmpty(request.getParameter("page")) == false) {
            try {
                pageIndex = Integer.parseInt(request.getParameter("page"));
            } catch (Exception e) {
            }
        }
        String searchUrl = "/fahuo/order_send_list";
        model.addAttribute("searchUrl", searchUrl);

        String orderNum = request.getParameter("orderNum");
        model.addAttribute("orderNum", orderNum);

        String mobile = request.getParameter("mobile");
        model.addAttribute("mobile", mobile);

        String logisticsCode = request.getParameter("logisticsCode");
        model.addAttribute("logisticsCode", logisticsCode);

        String startTime = null;

        if (StringUtils.isEmpty(request.getParameter("startTime")) == false) {
            startTime = request.getParameter("startTime");
            model.addAttribute("startTime", startTime);
        }

        String endTime = null;

        if (StringUtils.isEmpty(request.getParameter("endTime")) == false) {
            endTime = request.getParameter("endTime");
            model.addAttribute("endTime", endTime);
        }
        Integer shopId = null;
        if (StringUtils.isEmpty(request.getParameter("shopId")) == false) {
            shopId = Integer.parseInt(request.getParameter("shopId"));
            model.addAttribute("shopId", shopId);
        }
        Integer supplierId = null;
        if (StringUtils.isEmpty(request.getParameter("supplierId")) == false) {
            supplierId = Integer.parseInt(request.getParameter("supplierId"));
            model.addAttribute("supplierId", supplierId);
        }
        Integer status = 0;
        if (StringUtils.isEmpty(request.getParameter("status")) == false) {
            status = Integer.parseInt(request.getParameter("status"));
        }
        model.addAttribute("status", status);
        
        Integer isSettle = null;
        if (StringUtils.isEmpty(request.getParameter("isSettle")) == false) {
            isSettle = Integer.parseInt(request.getParameter("isSettle"));
            model.addAttribute("isSettle", isSettle);
        }

        var shopList = shopService.shopListShow();
        model.addAttribute("shopList", shopList);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);

        var result = orderSendService.getList(pageIndex, pageSize, status, orderNum, mobile, logisticsCode, startTime,
                endTime, shopId,isSettle,supplierId);

        model.addAttribute("list", result.getList());
        model.addAttribute("totalSize", result.getTotalSize());

        // 快递公司
        model.addAttribute("company", expressCompanyService.getExpressCompany());
        // 获取供应商
        List<ContactEntity> supplierList = contactService.getList(ContactTypeEnum.Supplier);
        model.addAttribute("supplierList", supplierList);

        model.addAttribute("view", "fahuo_order");
        model.addAttribute("pView", "ck");

        return "fahuo/order_send_list";
    }

    /***
     * 订单发货单（打印页面）
     * 
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/order_send_invoice", method = RequestMethod.GET)
    public String getInvoiceSendDetail(Model model, HttpServletRequest request, @RequestParam Long id) {
        // 查询订单信息
        var order = orderSendService.getOrderAndItemsById(id);
        model.addAttribute("order", order);
        return "fahuo/order_send_invoice";
    }


    @RequestMapping(value = "order_send_list_export_txt", method = { RequestMethod.POST, RequestMethod.GET })
    @ResponseBody
    public void outExportTxt(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
       
        String fileName = "";//
        Integer supplierId = null;
        Integer status = null;
        if (!StringUtils.isEmpty(request.getParameter("supplierId"))) {
            supplierId = Integer.parseInt(request.getParameter("supplierId"));
        }else return;

        if (!StringUtils.isEmpty(request.getParameter("status"))) {
            status = Integer.parseInt(request.getParameter("status"));
        }else return;
        // 按条件搜索
        var orderList = orderSendService.getList(status,supplierId,0);
        if(orderList == null || orderList.size() ==0) return;
        StringBuilder sb = new StringBuilder();
        // 循环写入数据
        for (int i = 0; i < orderList.size(); i++) {
            var orderVo = orderList.get(i);
            fileName = orderVo.getSupplierNumber();
            String goodsStr = "";
            for (var oi : orderVo.getItems()) {
                String goods = "";
                goods += "【";
                goods+=oi.getGoodsNumber();
                goods+=" - "+oi.getGoodsSpec();
                goods+=" (数量：x"+oi.getQuantity()+")";
                goods+="】";
                goodsStr+= goods;
            }

            sb.append(goodsStr);
            sb.append("\r\n");
            sb.append(orderVo.getOrderSn());
            sb.append("\r\n");
            //收货人
            sb.append(orderVo.getConsignee()+"\r\n");
            sb.append(orderVo.getMobile()+"\r\n");
            sb.append(orderVo.getAddress());
            sb.append("\r\n");
            sb.append("\r\n");
        }

        String text =sb.toString();
        SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
        String date = newsdf.format(new Date());

         //设置文件的名称和格式
         response.addHeader("Content-Disposition", "attachment;filename="
         + fileName+date+".txt");


        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(text.getBytes("UTF-8"));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            //LOGGER.error("导出文件文件出错:{}",e);
        } finally {
            try {
                buff.close();
                outStr.close();
            } catch (Exception e) {
                //LOGGER.error("关闭流对象出错 e:{}",e);
            }
        }

    }

    /**
     * 订单导出
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/order_send_list_export", method = { RequestMethod.POST, RequestMethod.GET })
    @ResponseBody
    public void outExport(HttpServletRequest request, HttpServletResponse response) {
        Integer supplierId = null;
        Integer status = null;
        if (!StringUtils.isEmpty(request.getParameter("supplierId"))) {
            supplierId = Integer.parseInt(request.getParameter("supplierId"));
        }else return;

        if (!StringUtils.isEmpty(request.getParameter("status"))) {
            status = Integer.parseInt(request.getParameter("status"));
        }else return;

        // 按条件搜索
        var orderList = orderSendService.getList(status,supplierId,0);
        if(orderList == null || orderList.size() ==0) return;

        /*************** 根据店铺查询订单导出的信息 *****************/
        String excelFileName = "";// excel文件名前缀

        // 创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = null;
        HSSFCell cell = null;
        // 第一行为空
        row = sheet.createRow(0);

        cell = row.createCell(0);
        cell.setCellValue("订单号");
        cell = row.createCell(1);
        cell.setCellValue("平台");

        cell = row.createCell(2);
        cell.setCellValue("下单时间");

        cell = row.createCell(3);
        cell.setCellValue("商品信息");

        cell = row.createCell(4);
        cell.setCellValue("总数量");

        cell = row.createCell(5);
        cell.setCellValue("收货信息");

        cell = row.createCell(6);
        cell.setCellValue("备注");

        cell = row.createCell(7);
        cell.setCellValue("发货物流");

        cell = row.createCell(7);
        cell.setCellValue("物流单号");

        cell = row.createCell(9);
        cell.setCellValue("商品金额");
        cell = row.createCell(10);
        cell.setCellValue("运费");



        int currRowNum = 0;
        // 循环写入数据
        for (int i = 0; i < orderList.size(); i++) {
            currRowNum++;
            
            // 写入订单
            var orderVo = orderList.get(i);
            excelFileName = orderVo.getSupplierNumber();

            //创建行
            row = sheet.createRow(currRowNum);

            //订单编号
            cell = row.createCell(0);
            cell.setCellValue(orderVo.getOrderSn());

            String shopTypeName = "";
            if(orderVo.getShopType().intValue() == 4) shopTypeName = "淘宝";
            else if(orderVo.getShopType().intValue() == 5) shopTypeName = "拼多多";
            else if(orderVo.getShopType().intValue() == 6) shopTypeName = "抖店";
            else shopTypeName = "其他";
            cell = row.createCell(1);
            cell.setCellValue(shopTypeName);

            //下单时间
            cell = row.createCell(2);
            cell.setCellValue(orderVo.getOrderTime());

            //商品
            cell = row.createCell(3);
            //组合
            int total = 0;
            String goodsStr = "";
            for (var oi : orderVo.getItems()) {
                String goods = "";
                goods += "【";
                goods+=oi.getGoodsNumber();
                goods+=" - "+oi.getGoodsSpec();
                goods+=" (数量：x"+oi.getQuantity()+")";
                goods+="】";
                goodsStr+= goods;
                total += oi.getQuantity();
            }

            cell.setCellValue(goodsStr);

            //总数量
            cell = row.createCell(4);
            cell.setCellValue(total);

            ////收货人
            cell = row.createCell(5);
            String s = "";
            s+=orderVo.getConsignee()+"\r\n";
            s+=orderVo.getMobile()+"\r\n";
            s+=orderVo.getAddress();

            cell.setCellValue(s);

            //备注
            cell = row.createCell(6);
            cell.setCellValue(orderVo.getRemark());

            
            // cell = row.createCell(7);
            // cell.setCellValue("");

        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((excelFileName + date + ".xls").getBytes("GBK"),
                            "ISO8859_1")
                    + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }

        return;
    }

    /**
     * 批量生产采购单
     * 
     * @param model
     * @param ids
     * @param request
     * @return
     */
    @RequestMapping(value = "/generate_purchase_for_order_send_list", method = RequestMethod.POST)
    public String generatePurr(Model model, @RequestParam("ids") String ids, HttpServletRequest request) {
        model.addAttribute("view", "fahuo_order");
        model.addAttribute("pView", "ck");

        var itemList = orderSendService.getItemListByOrderIds(ids);

        model.addAttribute("itemList", itemList);

        model.addAttribute("time", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        model.addAttribute("month", new SimpleDateFormat("yyyyMM").format(new Date()));

        // 生成单据编号
        String billNo = "PUR" + OrderNumberUtils.getOrderIdByTime();
        model.addAttribute("billNo", billNo);

        // 采购单来源
        model.addAttribute("transType", InvoiceTransTypeEnum.OrderDaiFa.getIndex());
        // 本次所选订单id
        model.addAttribute("srcOrderId", ids);

        // 获取供应商
        List<ContactEntity> contacts = contactService.getList(ContactTypeEnum.Supplier);
        model.addAttribute("contacts", contacts);

        return "fahuo/purchase_generate_for_order_send_list";
    }

    /**
     * 发货日报
     * @param model
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/order_send_daily", method = RequestMethod.GET)
    public String order_send_daily(Model model, HttpServletRequest request) {
        
        String startDate = DateUtil.customizeDate_(1);
        if (!StringUtils.isEmpty(request.getParameter("date"))){
            startDate = request.getParameter("date") ;
        }
        model.addAttribute("date",startDate);
        String endDate = "";
        if (!StringUtils.isEmpty(request.getParameter("endDate"))){
            endDate = request.getParameter("endDate") ;
        }
        model.addAttribute("endDate",endDate);

        Integer shopId = null;
        if(StringUtils.hasText(request.getParameter("shopId"))){
            shopId = Integer.parseInt(request.getParameter("shopId")) ;
            model.addAttribute("shopId", shopId);
        }

    

        Integer userId = DataConfigObject.getInstance().getLoginUserId();
        //有权限的店铺列表
        List<DcShopEntity> shops = shopService.getShopListByUserId(userId,null);//type=5是拼多多
        model.addAttribute("shops", shops);

        var report = orderSendService.getSendReport(shopId,startDate,endDate);
        model.addAttribute("report", report);

        model.addAttribute("view", "fahuo_daily");
        model.addAttribute("pView", "ck");

        return "fahuo/order_send_daily";
    }


}
